<template>
  <BasicModal :width="1650" v-bind="$attrs" :title="getTitle"
    :canFullscreen="false" :centered="true" :destroyOnClose="true" :showCancelBtn="false" :showOkBtn="false"
    :bodyStyle="{height:'calc(100vh - 150px)', overflow:'hidden'}"
    @register="registerModal"
  >
    <BasicTable  @register="registerTable" :onRowClick="handleClick" :rowClassName="rowClassName" :loading="loading">
    </BasicTable>
    <!-- 选中单元格合计显示区域 -->
    <div v-if="cells.length > 0" class="selected-cells-summary">
      <span class="summary-title">选中：</span>
      <span class="value">{{ cells.map(cell => formatAmount(cell)).join(' + ') }}</span>
      <span class="label"> = </span>
      <span class="value text-blue-500">{{ formatAmount(sumCells) }}</span>
      <span class="summary-title" style="display: inline-block; margin-left: 10px;">数量：{{ cells.length }}</span>
      <a-button type="link" size="small" @click="clearCells">清空选择</a-button>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import {ref, computed, unref, reactive, toRaw, h} from 'vue';
  import {BasicModal, useModalInner} from '/@/components/Modal';
  import {BasicTable, TableAction, ActionItem, BasicColumn} from '/@/components/Table';
  import {dateFormat, filterObj, formatAmount} from '/@/utils/common/compUtils';
  import {useListPage} from '/@/hooks/system/useListPage';
  import {findBalanceCheckAnalyse} from '/@/views/full/bank/types/bank.api';

  // Emits声明
  const emit = defineEmits(['register','success']);

  //----------定义变量 开始-------------------------------------------------------------
  const queryParam  = reactive<any>({});
  //标题
  const getTitle = ref<any>('');
  const isUpdate = ref(true);
  const bankRunningList = reactive<any>([]);

  const cells = ref<number[]>([]);

  // 当前选中的单元格信息
  const selectedCell = reactive({
    rowData: null,
    column: '',
    value: '',
    rowIndex: -1
  });

  /**
   * 对账结果表格样式
   * @param text 
   * @param record 
   */
  const getCellStyle = ({ text, record }) => {
    return h('div', { style: { backgroundColor: '#ffeeee', margin: '-8px', padding: '8px'} }, formatAmount(text));
  }

  /**
   * 累计求和 - 修复计算属性
   */
  const sumCells = computed(() => {
    if (cells.value.length === 0) return 0;
    return cells.value.reduce((sum, cell) => sum + (cell || 0), 0);
  });

  /**
   * 清空单元格数据
   */
  function clearCells() {
    cells.value = [];
    selectedCell.rowData = null;
    selectedCell.column = '';
  }

  /**
   * 单元格点击事件处理
   * @param record 行数据
   * @param column 列信息
   * @param event 事件对象
   */
  const handleCellDoubleClick = (record, column, event) => {
    // 获取单元格的值
    const cellValue = record[column.dataIndex];
    
    // 更新选中的单元格信息
    selectedCell.rowData = record;
    selectedCell.column = column.title;
    selectedCell.value = cellValue;
    selectedCell.rowIndex = record.id;
    
    cells.value.push(cellValue || 0);

  }

  /**
   * 为列配置单元格点击事件
   * @param column 列配置
   * @returns 带点击事件的列配置
   */
  const createColumnWithClick = (column) => {
    return {
      ...column,
      customCell: (record, rowIndex) => {
        return {
          onDblclick: (event) => handleCellDoubleClick(record, column, event),
          style: {
            cursor: 'pointer',
            userSelect: 'none'
          }
        };
      }
    };
  }

  //表单赋值
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    //console.log('BankBalanceCheck@@@@@useModalInner', data);
    let record = data?.record || {};
    getTitle.value       = record?.title;
    queryParam.bankId    = record?.bankId;
    queryParam.beginDate = record?.beginDate;
    queryParam.insider   = "";
    searchQuery();
  });

  // --------------右边--列表----------------------------------------
  // 订单列表 - 表头（添加单元格点击事件）
  const columns: BasicColumn[] = [
    createColumnWithClick({ title: '银行名称', align: 'left', dataIndex: 'djm', className:"text-12px", width: 140 }),
    createColumnWithClick({ title: '银行收入', align: 'right', dataIndex: 'srje01', width: 80, className:"text-green-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '银行支出', align: 'right', dataIndex: 'zcje01', width: 80, className:"text-red-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '银行差额', align: 'right', dataIndex: 'lrje01', width: 80, className:"text-purple-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '系统收入', align: 'right', dataIndex: 'srje02', width: 80, className:"text-green-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '系统支出', align: 'right', dataIndex: 'zcje02', width: 80, className:"text-red-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '系统差额', align: 'right', dataIndex: 'lrje02', width: 80, className:"text-purple-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '收入差额', align: 'right', dataIndex: 'srje12', width: 80, className:"text-green-500 text-12px", customRender: getCellStyle }),
    createColumnWithClick({ title: '支出差额', align: 'right', dataIndex: 'zcje12', width: 80, className:"text-red-500 text-12px", customRender: getCellStyle }),
    createColumnWithClick({ title: '银行差额', align: 'right', dataIndex: 'lrje12', width: 80, className:"text-purple-500 text-12px", customRender: getCellStyle }),
    createColumnWithClick({ title: '订单收入', align: 'right', dataIndex: 'srje03', width: 80, className:"text-green-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '订单支出', align: 'right', dataIndex: 'zcje03', width: 80, className:"text-red-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '订单差额', align: 'right', dataIndex: 'lrje03', width: 80, className:"text-purple-500 text-12px", customRender: ({text}) => formatAmount(text) }),
    createColumnWithClick({ title: '收入差额', align: 'right', dataIndex: 'srje23', width: 80, className:"text-green-500 text-12px", customRender: getCellStyle }),
    createColumnWithClick({ title: '支出差额', align: 'right', dataIndex: 'zcje23', width: 80, className:"text-red-500 text-12px", customRender: getCellStyle }),
    createColumnWithClick({ title: '订单差额', align: 'right', dataIndex: 'lrje23', width: 80, className:"text-purple-500 text-12px", customRender: getCellStyle }),
  ];

  // 列表页面公共参数、方法
  const loading = ref<boolean>(false);
  const { prefixCls, tableContext } = useListPage({
    designScope: 'bankBalance-analyse',
    tableProps: {
      rowKey: "id",
      size: "small",
      api: findBalanceCheckAnalyse,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: false, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 70,
      pagination: false,
      showSummary: true,
      immediate: false,
      summaryFunc: handleSummary,
    }
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;

  // --------------右边--列表----------------------------------------

  // --------------组件--事件----------------------------------------
  //单击行
  let selectRows = reactive<any>({ id: '' });
  function handleClick(record) {
    selectRows.id   = record.id;
  }

  //双击行
  function handleDblclick(record) {
    //handleEdit();
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  /**
   * 查询
   */
  function searchQuery() {
    let params = toRaw(filterObj(queryParam));
    setProps({ searchInfo: params });
    reload();
  }
    
  /**
   * 合计
   */
  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource()
    redoHeight();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }

</script>

<style lang="less" scoped>
  :deep(.ant-input-number .ant-input-number-input) {
    padding: 0 3px !important;
  }
  :deep(.ant-input-affix-wrapper) {
    padding: 0px !important;
  }

  // 添加单元格点击样式
  :deep(.ant-table-tbody > tr > td) {
    transition: background-color 0.2s;
  }

  :deep(.ant-table-tbody > tr > td:hover) {
    background-color: #f0f7ff !important;
  }

  // 选中的单元格样式
  :deep(.cell-selected) {
    background-color: #e6f7ff !important;
    border: 1px solid #1890ff !important;
  }
</style>